package com.homework.api_code.services.impl;

import com.homework.dao.domain.Code;
import com.homework.dao.mapper.CodeMapper;
import com.homework.util.ResultMsg;
import com.homework.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.apache.dubbo.config.annotation.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import com.homework.interface_code.services.CodeService;

@Service
public class CodeServiceImpl implements CodeService {
    @Autowired
    protected CodeMapper codeMapper;

    protected static int[] CODE_MAP = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    protected static int SIZE = 4; //4位长度

    private static final int CODE_ERR = 1;
    private static final int CODE_TIMEOUT = 2;

    private static final int TIME_EXPIRE = 600;//过期时间 10分钟


    public String generateCode() {
        Random r = new Random();

        String code = "";
        for(int i = 0; i < SIZE; i++)  {
            int num = r.nextInt(10);
            code += Integer.toString(CODE_MAP[num]);
        }

        return code;
    }

    public boolean saveCode(String email, String code) {
        Code code1 = new Code();
        code1.setEmail(email);
        code1.setCode(code);
        long now = System.currentTimeMillis();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        code1.setCreatetime(sf.format(new Date(now))); //
        code1.setExpiretime(sf.format(new Date(now + TIME_EXPIRE * 1000 )));

        return codeMapper.addCode(code1);
    }

    public ResultMsg validate(String email, String code)   {
        Code c = new Code();
        c.setCode(code);
        c.setEmail(email);
        Code code1 = codeMapper.validate(c);
        if(code1 == null) {
            return ResultUtil.error(CODE_ERR, "验证码错误");
        }

        try {
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date time = sf.parse(code1.getExpiretime());// 日期转换为时间戳
            long timestamp = time.getTime();
            if( timestamp < (System.currentTimeMillis() / 1000) ) {
                return ResultUtil.error(CODE_TIMEOUT, "验证码已过期");
            }
        } catch (Exception e) {
            return ResultUtil.error(CODE_ERR, "验证码错误");
        }

        return ResultUtil.success();
    }
}
